import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_select_item_for_list_page/common_select_item_for_list_page.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/common_title_edit_with_underline_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/camera/front_camera_head/front_camera_head_page.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/company_choose_terminal_list_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_branch_bean.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/bean/create_user_upload_bean.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/relative_stu/select_relative_stu_list_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/class_course_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/class_course_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_overall_location/user_branch_location.dart';
import 'package:e_reception_flutter/ui/create_user/user_overall_location/user_overall_location.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/cityWidget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/create_user_address/create_user_address_attend_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/departmentWidget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_class_course_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/multi_select_department_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/add_user_address_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/personal_class_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/projectWidget.dart';
import 'package:e_reception_flutter/ui/mypage/edit_name_dialog_widget.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/logo_detail_page.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'dart:math' as math;

/// 添加用户编辑框组件
///
/// @author: zengxiangxi
/// @createTime: 3/10/21 10:41 AM
/// @specialDemand:
class CreateUserEditWidget extends StatefulWidget {
  final CreateUserUploadBean uploadBean;
  final String role;
  final ValueNotifier<String> updateNameValueNotifier;

  const CreateUserEditWidget(
      {Key key, this.uploadBean, this.updateNameValueNotifier, this.role})
      : super(key: key);

  @override
  _CreateUserEditWidgetState createState() => _CreateUserEditWidgetState();
}

class _CreateUserEditWidgetState extends BaseState<CreateUserEditWidget> {
  ///是否显示项目和城市
  bool isShowProjectAndCity = false;

  ///是否显示身份和终端
  bool isShowIdentityAndTerminal = false;

  TextEditingController _nameController;

  TextEditingController _terminalController;
  TextEditingController _departmentController;
  TextEditingController _classController;
  TextEditingController _addressController;
  List<ClassInfoBean> classInfoBeanList = List<ClassInfoBean>();
  FaceUserInfoBean infoBean = new FaceUserInfoBean();
  UserBranchLocationUtil locationUtil;
  List<CompanyBranchListInfoBean> branchUserLocation;
  VgLocation _locationPlugin;
  @override
  void initState() {
    super.initState();
    branchUserLocation = List<CompanyBranchListInfoBean>();
    _nameController = TextEditingController();
    locationUtil = UserBranchLocationUtil(this);
    widget.uploadBean.isManagerTerminal = isShowIdentityAndTerminal;
    widget.updateNameValueNotifier?.addListener(_processUpdateName);
    _terminalController = TextEditingController(
        text: _getTerminalEditValueStr(widget.uploadBean.terminalList));
    _departmentController = TextEditingController(text: "");
    _classController = TextEditingController(text: "");
    _addressController = TextEditingController(text: "");
    Future<String> latlng = VgLocationUtils.getCacheLatLngString();
    latlng.then((value){
      print("使用缓存gps:" + value);
      locationUtil.userLocationInfoGps(value);
    });
    _locationFristGps();
  }

  void _processUpdateName() {
    final String updateName = widget.updateNameValueNotifier.value;
    if (_nameController == null) {
      return;
    }
    widget.uploadBean.nick = updateName;
    _nameController.text = _getNameAndNickSplitStr();
  }

  void _locationFristGps(){
    locationUtil?.valueNotifier?.addListener(() {
      branchUserLocation = locationUtil?.valueNotifier?.value;
      setState(() { });
      if((branchUserLocation?.length??0)==0){
        return;
      }
      _addressController?.text = branchUserLocation[0]?.getAddressStr()?.toString();
      widget.uploadBean.cbid = branchUserLocation[0]?.cbid;
    });
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocationWithoutCheckPermission((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        print("添加用户最新gps:" + value);
        locationUtil.userLocationInfoGps(value);
      });
    });
  }

  @override
  void dispose() {
    widget.updateNameValueNotifier.removeListener(_processUpdateName);
    _terminalController.dispose();
    _classController.dispose();
    _addressController?.dispose();
    _departmentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return Column(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        _toOneMineWidget(),
        // Spacer(),
        SizedBox(height: 10,),
        _toManagerTerminalBarWidget(),
        Container(
          height: ScreenUtils.getBottomBarH(context),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        )
      ],
    );
  }

  Widget _toOneMineWidget() {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          SizedBox(
            height: 10,
          ),
          _toClassifyAndIdRowWidget(),
          Container(
              height: 10,
              color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
          _toNameAndPhoneRowWidget(),
          Container(
              height: 10,
              color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
          _parentRelativeStuWidget(),
          _StudentRelativeStuWidget(),
          _toHideOrShowStaffWidget(),
          if(AppOverallDistinguish.comefromAiOrWeStudy() && UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition())
          _toAddressWidget(),
          // _toHideOrShowGradeWidget(),
        ],
      ),
    );
  }

  Widget _toHideOrShowStaffWidget() {
    return Offstage(
      offstage: !(widget.uploadBean.groupBean?.isStaff() ?? false),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _toDepartmentWidget(),
          Offstage(
            offstage: true,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                _toSplitLineWidget(),
                _toProjectWidget(),
                _toSplitLineWidget(),
                _toCityWidget(),
              ],
            ),
          ),
          //更多信息注释，直接展示出来
          // _toMoreButtonWidget(),
        ],
      ),
    );
  }

  ///是否隐藏和显示班级
  Widget _toHideOrShowGradeWidget() {
    return Offstage(
      offstage: !(widget.uploadBean.groupBean?.isStudent() ?? false),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          // _toCourseWidget(),
          // _toSplitLineWidget(),
          _toGradeWidget(),
        ],
      ),
    );
  }

  // Widget _toCourseWidget() {
  //   return _EditTextWidget(
  //     title: "课程",
  //     hintText: "请选择",
  //     isShowGoIcon: true,
  //     onTap: (String editText, dynamic value) {
  //       return CourseClassWidget.navigatorPush(context,widget.uploadBean.courseList);
  //     },
  //     onDecodeResult: (dynamic result) {
  //       if (result is! List<CourseClassListItemBean>) {
  //         return null;
  //       }
  //       return EditTextAndValue(
  //           value: result,
  //           editText: (result?.length ?? 0) <= 0 ? "" : "${result.length}个课程");
  //     },
  //     onChanged: (String editText, dynamic value) {
  //       widget.uploadBean.courseList = value;
  //     },
  //   );
  // }

  Widget _toGradeWidget() {
    return EditTextWidget(
      title: "班级",
      hintText: "请选择",
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return ClassCourseWidget.navigatorPush(
            context, widget.uploadBean.classList);
      },
      onDecodeResult: (dynamic result) {
        if (result is! List<ClassCourseListItemBean>) {
          return null;
        }
        return EditTextAndValue(
            value: result,
            editText: (result?.length ?? 0) <= 0 ? "" : "${result.length}个班级");
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.classList = value;
      },
    );
  }

  Widget _toNameAndPhoneRowWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              EditTextWidget(
                title: "姓名",
                hintText: (widget.uploadBean.groupBean?.isParent() ?? false)
                    ? '如“张三的家长”'
                    : "请输入",
                isShowRedStar: true,
                // autofocus: true,
                isFollowEdit: true,
                controller: _nameController,
                onTap: StringUtils.isEmpty(widget.uploadBean.nick)
                    ? null
                    : (String editText, dynamic value) {
                        return EditNameDialogWidget.navigatorPushDialog(context,
                            widget.uploadBean.name, widget.uploadBean.nick);
                      },
                onDecodeResult: (dynamic result) {
                  if (result == null || result is! Map) {
                    return null;
                  }
                  widget.uploadBean.name =
                      result[EDIT_NAME_AND_NICK_BY_NAME_KEY];
                  widget.uploadBean.nick =
                      result[EDIT_NAME_AND_NICK_BY_NICK_KEY];
                  _nameController.text = _getNameAndNickSplitStr();
                  return null;
                },
                onChanged: (String editText, dynamic value) {
                  widget.uploadBean.name = editText;
                  widget.uploadBean.nick = value;
                },
              ),
              _toSplitLineWidget(),
              EditTextWidget(
                title: "手机",
                hintText: "请输入",
                keyboardType: TextInputType.number,
                inputFormatters: [
                  WhitelistingTextInputFormatter(RegExp("[0-9+]")),
                  LengthLimitingTextInputFormatter(DEFAULT_PHONE_LENGTH_LIMIT)
                ],
                isShowRedStar: widget.uploadBean.phoneRedStar(),
                onChanged: (String editText, dynamic value) {
                  widget.uploadBean.phone = editText;
                },
              ),
            ],
          ),
        ),
        SizedBox(
          width: 15,
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            onClickUserLogo();
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(2),
            child: Container(
              width: 90,
              height: 90,
              child: StringUtils.isNotEmpty(widget.uploadBean.headFaceUrl)
                  ? VgCacheNetWorkImage(
                      widget.uploadBean.headFaceUrl,
                      imageQualityType: ImageQualityType.middleUp,
                    )
                  : Image.asset("images/create_user_head_ico.png"),
            ),
          ),
        ),
        SizedBox(width: 15),
      ],
    );
  }

  void onClickUserLogo() {
    FocusScope.of(context).requestFocus(FocusNode());
    if (StringUtils.isNotEmpty(widget?.uploadBean?.headFaceUrl)) {
      LogoDetailPage.navigatorPush(context,
          url: widget?.uploadBean?.headFaceUrl,
          selectMode: SelectMode.HeadBorder,
          clipCompleteCallback: (path, cancelLoadingCallback) {
            widget.uploadBean.headFaceUrl = path;
            setState(() {});
          }
      );
      return;
    }
    addUserLogo();
  }

  void addUserLogo() {
    CommonMoreMenuDialog.navigatorPushDialog(context, {
      "上传图片": () async {
        String path = await ClipImageHeadBorderUtil.clipOneImage(context,
          scaleY: 1, scaleX: 1, maxAutoFinish: true,
        isCanCapture: false,
        isShowHeadBorderWidget: true);
        if (path == null || path == "") {
          return;
        }
        widget.uploadBean.headFaceUrl = path;
        setState(() {});
      },
      "拍照": () async {
        String path = await FrontCameraHeadPage.navigatorPush(context);
        if (path == null || path.isEmpty) {
          return;
        }
        widget.uploadBean.headFaceUrl = path;
        setState(() {});
      }
    });
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      padding: const EdgeInsets.only(left: 15),
      height: 0.5,
      child: Container(
        color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      ),
    );
  }

  ///分类 家长不显示编号
  Widget _toClassifyAndIdRowWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: EditTextWidget(
            title: "分类",
            hintText: "请选择",
            isShowRedStar: true,
            customWidget: (Widget titleWidget, Widget textFieldWidget,
                Widget leftWidget, Widget rightWidget) {
              return Row(
                children: <Widget>[
                  leftWidget,
                  Expanded(
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () async {
                        GroupListBean groupListBean =
                            await CommonSelectItemForListPage.navigatorPush<
                                    GroupListBean>(context,
                                title: "分类选择",
                                selectedItem: widget.uploadBean.groupBean,
                                list: UserRepository.getInstance()
                                    .userData
                                    ?.companyInfo
                                    ?.groupList,
                                getTextFunc: (GroupListBean groupItemBean) {
                          return groupItemBean?.groupName;
                        });
                        if (groupListBean == null) {
                          return;
                        }
                        widget.uploadBean.groupBean = groupListBean;
                        setState(() {});
                      },
                      child: Row(
                        children: <Widget>[
                          titleWidget,
                          CommonConstraintMaxWidthWidget(
                            maxWidth: ScreenUtils.screenW(context) / 4,
                            child: Text(
                              showOriginEmptyStr(
                                      widget.uploadBean.groupBean?.groupName) ??
                                  "请选择",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: Color(0xFFD0E0F7),
                                fontSize: 14,
                              ),
                            ),
                          ),
                          (widget.uploadBean.groupBean?.isParent() ?? false)
                              ? Spacer()
                              : SizedBox(
                                  width: 0,
                                ),
                          Padding(
                            padding: const EdgeInsets.only(
                                left: 15, right: 15, top: 2),
                            child: Image.asset(
                              "images/go_ico.png",
                              width: 6,
                              color: VgColors.INPUT_BG_COLOR,
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        ),
        (widget.uploadBean.groupBean?.isParent() ?? false)
            ? SizedBox(
                width: 1,
              )
            : Expanded(
                //家长不显示编号
                child: EditTextWidget(
                  title: "编号",
                  hintText: "员工号/学号等",
                  isShowRedStar: false,
                  isGoneRedStar: true,
                  autofocus: false,
                  onChanged: (String editText, dynamic value) {
                    widget.uploadBean.userNumber = editText;
                  },
                ),
              )
      ],
    );
  }

  Widget _toDepartmentWidget() {
    return EditTextWidget(
      title: "所在部门",
      hintText: "请选择",
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return DepartmentWidget.navigatorPush(
            context, widget.uploadBean?.departmentId,fuid:widget?.uploadBean?.fuid);
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.departmentId = value;
        widget.uploadBean.departmentName = editText;
      },
    );
  }

  Widget _toAddressWidget() {
    return EditTextWidget(
      controller: _addressController,
      title: "刷脸地址",
      hintText: "请选择",
      isShowGoIcon: true,
      isShowRedStar: true,
      onTap: (String editText, dynamic value) {
        return AddUserAddressAttendPage.navigatorPush(
            context, branchUserLocation,"","",
            createEdit: true).then((value){
              if(value!=null && (branchUserLocation?.length??0)!=0){
                branchUserLocation = value;
                List<String> cbids = [];
                branchUserLocation?.forEach((element) {
                  cbids?.add(element?.cbid);
                });
                widget.uploadBean.cbid = VgStringUtils.getSplitStr(cbids, symbol: ",");
                if(cbids?.length==1){
                  _addressController?.text = branchUserLocation[0]?.getAddressStr();
                }else{
                  _addressController?.text = branchUserLocation[0]?.getAddressStr()+"等${value?.length}个地址";
                }

              }
        });
      },
    );
  }

  Widget _toProjectWidget() {
    return EditTextWidget(
      title: "所在项目",
      hintText: "请选择",
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return ProjectWidget.navigatorPush(
            context, widget.uploadBean?.projectId);
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.projectId = value;
        widget.uploadBean.projectName = editText;
      },
    );
  }

  Widget _toCityWidget() {
    return EditTextWidget(
      title: "城市",
      hintText: "请选择",
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return CityWidget.navigatorPush(context, widget.uploadBean?.cityId);
      },
      onDecodeResult: (dynamic result) {
        if (result is! EditTextAndValue) {
          return null;
        }
        return result;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.cityId = editText;
        widget.uploadBean.cityName = editText;
      },
    );
  }

  ///更多按钮
  Widget _toMoreButtonWidget() {
    return Offstage(
      offstage: isShowProjectAndCity,
      child: GestureDetector(
        onTap: () {
          VgToolUtils.removeAllFocus(context);
          isShowProjectAndCity = true;
          setState(() {});
        },
        child: Container(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          padding: const EdgeInsets.only(top: 13, bottom: 30),
          child: Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  "更多信息",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 12,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 3),
                  child: Icon(
                    Icons.keyboard_arrow_down,
                    color: VgColors.INPUT_BG_COLOR,
                    size: 14,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  ///家长身份 显示关联学员接口
  _parentRelativeStuWidget() {
    return Visibility(
        visible:  widget.uploadBean.groupBean?.isParent()??false,
        child: EditTextWidget(
          title: "关联学员",
          hintText: "请选择",
          isShowGoIcon: true,
          isShowRedStar: false,
          readOnly: true,
          onTap: (String editText, dynamic value) {
            GroupListBean stuListBean = UserRepository.getInstance()
                .userData
                ?.companyInfo
                ?.groupList
                ?.firstWhere((element) => element.isStudent(),
                    orElse: () {
              return null;
            });
            //学员groupid
            // String groupid = stuListBean?.groupid ?? null;

            return SelectRelativeStuListPage.navigatorPush(
                context, widget.uploadBean?.relativeStuIds, stuListBean,null);
          },
          onDecodeResult: (dynamic result) {
            if (result is! Map) {
              return null;
            }

            EditTextAndValue editTextAndValue = EditTextAndValue(
              editText: result['name'],
              value: result['ids'],
            );
            return editTextAndValue;
          },
          onChanged: (String editText, dynamic value) {
            widget.uploadBean.relativeStuIds = value;
          },
        ));
  }

  ///家长身份 显示关联学员接口
  _StudentRelativeStuWidget() {

    infoBean.classInfo = classInfoBeanList;
    return Visibility(
        visible:  widget.uploadBean.groupBean?.isStudent()??false,
        child: EditTextWidget(
          title: "所在班级",
          hintText: "请选择",
          isShowGoIcon: true,
          isShowRedStar: false,
          readOnly: true,
          onTap: (String editText, dynamic value) {
            //跳转到对应的信息编辑界面
         return  PersonalClassWidget.navigatorPush(context, infoBean,"CreateUserPage");
          },
          onDecodeResult: (dynamic result) {

            String textList = "";
            List<String> classTextList = new List();
            List<ClassCourseListItemBean> classNameList = result;
            classNameList?.forEach((element) {
              ClassInfoBean classInfoBean = ClassInfoBean();
              classTextList?.add(element?.name?.trim());
              classInfoBean?.classname = element?.name?.trim();
              classInfoBean?.classid = element?.id;
              classInfoBeanList?.add(classInfoBean);
            });
            textList = VgStringUtils?.getSplitStr(classTextList, symbol: "、");
            EditTextAndValue editTextAndValue = EditTextAndValue(
              editText: textList,
              value: classNameList,
            );
            return editTextAndValue;
          },
          onChanged: (String editText, dynamic value) {
            widget.uploadBean.classList = value;
          },
        ));
  }

  ///管理员权限 学员/家长不显示管理权限
  Widget _toManagerTerminalBarWidget() {
    return Visibility(
      visible:  widget.uploadBean.groupBean?.isStaff()??false,
      child: Container(
        constraints: BoxConstraints(minHeight: widget.role=='01'?280:250),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Container(
              height: 50,
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Row(
                children: <Widget>[
                  SizedBox(width: 15),
                  Text(
                    "管理权限",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Color(0xFFBFC2CC),
                      fontSize: 15,
                    ),
                  ),
                  Spacer(),
                  GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      isShowIdentityAndTerminal = !isShowIdentityAndTerminal;
                      widget.uploadBean.isManagerTerminal = isShowIdentityAndTerminal;
                      if(!isShowIdentityAndTerminal){
                        //关闭时将管理级别、终端、部门等清空
                        resetManagerData();
                      }else{
                        widget.uploadBean.identityType = CompanyAddUserEditInfoIdentityType.commonAdmin;
                        widget.uploadBean.identityName =
                            CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
                                '90')
                                .getTypeToStr();
                      }
                      //移除焦点
                      VgToolUtils.removeAllFocus(context);
                      setState(() {});
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Image.asset(
                        isShowIdentityAndTerminal
                            ? "images/switch_open.png"
                            : "images/switch_close.png",
                        width: 36,
                        gaplessPlayback: true,
                      ),
                    ),
                  )
                ],
              ),
            ),
            Visibility(
              visible: isShowIdentityAndTerminal,
              child: Container(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    _toIdentityWidget(),
                    _toCommonAdminTerminalWidget(), //管理终端
                    _toManageDepartmentWidget(), //管理部门
                    if(UserRepository.getInstance().getType()=="01"||UserRepository.getInstance().getType()=="03")
                    _toManageClassWidget() //管理班级

                    // Offstage(
                    //     offstage: !(widget.uploadBean.isCommonAdminRole()),
                    //     child: _toCommonAdminTermainlWidget()),
                    // Offstage(
                    //     offstage: !(widget.uploadBean.isSuperAdminRole()),
                    //     child: _toSuperAdminTerminalWidget()),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///管理级别、终端、部门等清空
  void resetManagerData() {
    widget.uploadBean.departmentList = null;
    widget.uploadBean.classIdList = null;
    widget.uploadBean.terminalList = null;
    _terminalController.text = "";
    _terminalController.clear();
    _departmentController.text = "";
    _classController.text = "";
    widget.uploadBean.identityType = CompanyAddUserEditInfoIdentityType.commonUser;
  }

  ///管理级别
  Widget _toIdentityWidget() {
    return EditTextWidget(
      title: "管理级别",
      hintText: "请选择",
      isShowGoIcon: true,
      isShowRedStar: true,
      initContent: widget.uploadBean.identityName??'',
      onTap: (String editText, dynamic value) {
        return SelectUtil.showListSelectDialog(
          context: context,
          title: "管理级别",
          positionStr: widget.uploadBean.identityName,
          textList: CompanyAddUserEditInfoIdentityExtension.getListStr(),
        );
      },
      onDecodeResult: (dynamic result) {
        if (result is String && StringUtils.isNotEmpty(result)) {
          return EditTextAndValue(
              editText: result,
              value:
                  CompanyAddUserEditInfoIdentityExtension.getStrToType(result));
        }
        return null;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.identityName = editText;
        if(widget.uploadBean.identityType==value){
          return;
        }
        widget.uploadBean.identityType = value;
        if (value == CompanyAddUserEditInfoIdentityType.superAdmin) {
          //超管时清空终端 部门 班级 （不用上传）
          widget.uploadBean.departmentList = null;
          widget.uploadBean.classIdList = null;
          widget.uploadBean.terminalList = null;
          _terminalController.text = "全部终端";
          _departmentController.text = "全部部门";
          _classController.text = "全部班级";
        }else{
          _terminalController.text = "";
          _departmentController.text = "";
          _classController.text = "";
        }

        setState(() {});
      },
    );
  }

  ///管理终端
  Widget _toCommonAdminTerminalWidget() {
    return Column(
      children: <Widget>[
        _toSplitLineWidget(),
        EditTextWidget(
          title: "管理终端",
          hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.terminalList?.length??0}台终端显示屏" : "请选择",
          isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),
          controller: _terminalController,
          initContent: _getTerminalEditValueStr(widget.uploadBean.terminalList),
          isShowRedStar: false,
          onTap: (String editText, dynamic value) {
            if (widget.uploadBean.isSuperAdminRole()) {
              return null;
            }
            return CompanyChooseTerminalListPage.navigatorPush(
                context, widget.uploadBean?.terminalList);
          },
          onDecodeResult: (dynamic result) {
            if (result is! List<CompanyChooseTerminalListItemBean>) {
              return null;
            }
            List<CompanyChooseTerminalListItemBean> resultList = result;

            EditTextAndValue editTextAndValue = EditTextAndValue(
              editText: _getTerminalEditValueStr(resultList),
              value: result,
            );
            return editTextAndValue;
          },
          onChanged: (String editText, dynamic value) {
            widget.uploadBean.terminalList = value;
          },
        ),
      ],
    );
  }

  ///管理部门
  Widget _toManageDepartmentWidget() {
    return Column(
      children: <Widget>[
        _toSplitLineWidget(),
        EditTextWidget(
            title: "管理部门",
            hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.departmentList?.length??0}个部门" : "请选择",
            isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),
            controller: _departmentController,
            initContent: '',
            isShowRedStar: false,
            onTap: (String editText, dynamic value) {
              if (widget.uploadBean.isSuperAdminRole()) {
                return null;
              }
              return MultiSelectDepartmentWidget.navigatorPush(context,
                  selectIds: widget.uploadBean?.departmentList,
                  multiSelect: true);
            },
            onDecodeResult: (dynamic result) {
              if (result is! EditTextAndValue) {
                return null;
              }
              return result;
            },
            onChanged: (String editText, dynamic value) {
              _departmentController?.text = splitDepartment(editText);
              widget.uploadBean?.departmentList = value;
            }),
      ],
    );
  }
  String splitDepartment(String managerDepartmentName){
    if(managerDepartmentName!=null && managerDepartmentName!=""){
      List<String>  departmentNames = List();
      if(managerDepartmentName.contains(",")){
        departmentNames = managerDepartmentName?.split(",");
      }else{
        departmentNames = managerDepartmentName?.split("、");
      }

      if(departmentNames?.length ==1){
        return managerDepartmentName;
      }else{
        return managerDepartmentName = "${departmentNames?.length}个部门";
      }
    }
    return managerDepartmentName;
  }

  ///管理班级
  _toManageClassWidget() {
    return Visibility(
      visible: widget.role != "00",
      child: Column(
        children: <Widget>[
          _toSplitLineWidget(),
          EditTextWidget(
              title: "管理班级",
              hintText: widget.uploadBean.isSuperAdminRole() ? "全部${widget?.uploadBean?.classIdList?.length??0}个班级" : "请选择",
              controller: _classController,
              isShowGoIcon: !widget.uploadBean.isSuperAdminRole(),
              isShowRedStar: false,
              onTap: (String editText, dynamic value) {
                if (widget.uploadBean.isSuperAdminRole()) {
                  return null;
                }
                return MultiSelectClassCourseWidget.navigatorPush(
                    context, widget.uploadBean.classIdList);
              },
              onDecodeResult: (dynamic result) {
                if (result is! EditTextAndValue) {
                  return null;
                }
                return result;
              },
              onChanged: (String editText, dynamic value) {
                _classController?.text = splitManagerClassName(editText);
                widget.uploadBean?.classIdList = value;
              }),
        ],
      ),
    );
  }
  String splitManagerClassName(String managerClassName){
    if(managerClassName==null && managerClassName=="")return managerClassName;
    List<String>  managerClassNames = List();
    if(managerClassName.contains(",")){
      managerClassNames = managerClassName?.split(",");
    }else{
      managerClassNames = managerClassName?.split("、");
    }

    if(managerClassNames?.length ==1){
      return managerClassName;
    }else{
      return managerClassName = "${managerClassNames?.length}个班级";
    }
  }

  Widget _toSuperAdminTerminalWidget() {
    return EditTextWidget(
      title: "管理终端",
      hintText: "管理终端",
      isShowRedStar: false,
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return CompanyChooseTerminalListPage.navigatorPush(
            context, widget.uploadBean?.terminalList);
      },
      onDecodeResult: (dynamic result) {
        if (result is! List<CompanyChooseTerminalListItemBean>) {
          return null;
        }
        List<CompanyChooseTerminalListItemBean> resultList = result;

        EditTextAndValue editTextAndValue = EditTextAndValue(
          editText: _getTerminalEditValueStr(resultList),
          value: result,
        );
        return editTextAndValue;
      },
      onChanged: (String editText, dynamic value) {
        widget.uploadBean.terminalList = value;
      },
    );
  }

  ///获取终端编辑值串
  String _getTerminalEditValueStr(
      List<CompanyChooseTerminalListItemBean> resultList) {
    String editTextStr;
    if (resultList == null || resultList.isEmpty) {
      editTextStr = "";
    } else if (resultList.length == 1) {
      editTextStr = resultList?.elementAt(0)?.terminalName;
      //处理空名字
      if (StringUtils.isEmpty(editTextStr)) {
        editTextStr = "1个终端";
      }
    } else {
      editTextStr = "${resultList?.length ?? 0}个终端";
    }
    return editTextStr;
  }

  String _getNameAndNickSplitStr() {
    StringBuffer stringBuffer = StringBuffer();
    if (StringUtils.isNotEmpty(widget.uploadBean.nick)) {
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(
          widget.uploadBean.name, 7,
          symbol: "..."));
    } else {
      stringBuffer.write(widget.uploadBean.name);
    }
    if (StringUtils.isNotEmpty(widget.uploadBean.nick)) {
      stringBuffer.write(" / ");
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(
          widget.uploadBean.nick, 7,
          symbol: "..."));
    }
    return stringBuffer.toString();
  }
}

/// 编辑框组件
///
/// @author: zengxiangxi
/// @createTime: 1/18/21 10:55 PM
/// @specialDemand:
class EditTextWidget extends StatelessWidget {
  final String title;

  final String hintText;

  final CommonTitleEditEditAndValueChangedCallback onChanged;

  ///点击
  final CommonTitleNavigatorPushCallback onTap;

  ///解析跳转返回值
  final CommonTitlePopResultDecodeCallback onDecodeResult;

  final bool isShowRedStar;

  ///中字极限
  final int maxZHCharLimit;

  ///极限字数回调
  final ValueChanged<int> limitCharFunc;

  ///限制
  final List<TextInputFormatter> inputFormatters;

  ///是否显示跳转icon
  final bool isShowGoIcon;

  ///初始化数据
  final String initContent;

  ///初始值
  final dynamic initValue;

  ///只读
  final bool readOnly;

  ///是否去掉红星
  final bool isGoneRedStar;

  ///是否跟随编辑框
  final bool isFollowEdit;

  final bool autofocus;

  final TextEditingController controller;

  final TextInputType keyboardType;

  final Function(Widget titleWidget, Widget textFieldWidget, Widget leftWidget,
      Widget rightWidget) customWidget;

  const EditTextWidget(
      {Key key,
      this.title,
      this.hintText,
      this.onChanged,
      this.isShowRedStar = false,
      this.onTap,
      this.onDecodeResult,
      this.maxZHCharLimit,
      this.limitCharFunc,
      this.inputFormatters,
      this.isShowGoIcon = false,
      this.initContent,
      this.initValue,
      this.readOnly,
      this.isGoneRedStar = false,
      this.isFollowEdit = false,
      this.customWidget,
      this.controller,
      this.keyboardType, this.autofocus = true})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CommonTitleEditWithUnderlineWidget(
      controller: controller,
      titleTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
          fontSize: 14),
      editTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          fontSize: 14),
      title: title,
      titleMarginRight: 15,
      height: 50,
      onChanged: onChanged,
      autofocus: autofocus ?? false,
      onDecodeResult: onDecodeResult,
      onTap: onTap,
      minLines: 1,
      maxLines: 1,
      readOnly: readOnly,
      maxZHCharLimit: maxZHCharLimit,
      limitCharFunc: limitCharFunc,
      inputFormatters: inputFormatters,
      customWidget: customWidget,
      keyboardType: keyboardType,
      lineMargin: const EdgeInsets.only(left: 15, right: 0),
      lineUnselectColor: Color(0xFF303546),
      lineHeight: 0,
      initContent: initContent,
      autoDispose: false,//自动移除监听 这里不要，会导致controller 改变值无效
      initValue: initValue,
      lineSelectedColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      hintText: hintText,
      hintTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextEditHintColor(),
          fontSize: 14),
      rightWidget: Offstage(
        offstage: !isShowGoIcon,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Image.asset(
            "images/go_ico.png",
            width: 6,
            color: VgColors.INPUT_BG_COLOR,
          ),
        ),
      ),
      leftWidget: Offstage(
        offstage: isGoneRedStar,
        child: Container(
          width: 15,
          child: Opacity(
            opacity: isShowRedStar ? 1 : 0,
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  "*",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getMinorRedColor_F95355(),
                      fontSize: 14,
                      height: 1.1),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


class EventAdmin{}